import axios from "axios";

const axiosInstance: any = axios.create({
  withCredentials: true,
  timeout: 10000,
  baseURL: "http://localhost:9191",
});

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  (config: any) => {
    console.log("请求拦截器", config);

    let headersData: any = {
      accept: "application/json",
      "Content-Type": "application/json;charset=UTF-8",
    };
    config.headers = {
      ...config.headers,
      ...headersData,
    };
    // 在发送请求之前做些什么
    return config;
  },
  (error: Record<string, any>) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response: any) => {
    return response;
  },
  (error: any) => {
    // 处理响应错误
    return Promise.reject(error);
  }
);
export async function get<T>(url: any, params?: any, token?: any) {
  let config: any = { params: params };
  if (token) {
    config = {
      params: params,
      headers: {
        token,
      },
    };
  }
  const _url: string = url;
  const response = await axiosInstance.get(_url, config);
  return response.data;
}

export async function post(url: string, data?: any) {
  const _url: string = url;
  const config: Record<string, any> = {
    withCredentials: true,
    headers: { "Content-Type": "application/json;charset=utf-8" },
  };
  const response = await axiosInstance.post(_url, data, config);
  return response.data;
}
export async function put(url: string, data?: any) {
  const response = await axiosInstance.put(url, data);
  return response.data;
}
export async function del(url: string, params?: any) {
  const response = await axiosInstance.delete(url, { params });
  return response.data;
}
export const request = axiosInstance;
